﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Common.Model;
using Common.PddApi;
using Dapper.Contrib.Extensions;
using Newtonsoft.Json.Linq;
using pinduoduo;
using pinduoduo.Model;
using pinduoduo.Service;
using pinduoduo.Util;
using RestSharp;
using Tk.Soc.Share.Common.Helpers;

namespace Common.Service
{
    public class PddService
    {
        public readonly PddTokenService pddTokenService;

        public PddService()
        {
            pddTokenService = new PddTokenService();
        }

        public static async void AfterSales(PddToken pddToken, Order order)
        {
            string address = string.Empty;
            string errorMsg = string.Empty;
            address = G_Api.GetProxyIp(pddToken.pdd_user_id,out errorMsg);
            if (string.IsNullOrWhiteSpace(address))
            {
                return;
            }

            var res = await pinduoduo.PddApi.AfterSalesTrigger(pddToken, order.orderSn, address);
            res = await pinduoduo.PddApi.AfterSalesAll(pddToken, order.orderSn, address);
            res = await pinduoduo.PddApi.AsmCouponCheck(pddToken, order.orderSn, address);

            AfterSales afterSales = new AfterSales(int.Parse(order.goodsMoney), "");
            afterSales.order_sn = order.orderSn;
            res = await pinduoduo.PddApi.AfterSales(pddToken, afterSales, address);

        }

        public static async Task<Tuple<string,string>> GetProxyIp(string pdd_user_id ,bool IsYunGet,string GetIpUrl = null)
        {
            string daili = "";
            string errorMsg = "";
            for (int i = 0; i < 5; i++)
            {
                if (IsYunGet)
                {
                    daili = G_Api.GetProxyIp(pdd_user_id,out errorMsg);
                    if (string.IsNullOrWhiteSpace(daili)) {
                        break;
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(GetIpUrl))
                    {
                        errorMsg = "请先添加提取ip的链接";
                        return null;
                    }
                    daili = IPProxy.GetProxyIp(GetIpUrl);
                    if (daili.Contains("套餐已过期"))
                    {
                        errorMsg = "代理不可用，请联系管理员";
                        return null;
                    }
                }

                string realIP = await G_Api.CheckIp(daili);
                if (string.IsNullOrWhiteSpace(realIP))
                {
                    errorMsg = "检测ip无效，重新获取 \r\n";
                    daili = "";
                }
                else
                {
                    //string str = "realIP";
                    //Match m = Regex.Match(str, @"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}");
                    //if (m.Success)
                    //{
                    //   // m.Value;
                    //    //MessageBox.Show(m.Value);
                    //}
                    errorMsg = "";
                    break;
                }
            }
        
            Tuple<string, string> tuple = new Tuple<string, string>(daili,errorMsg);
            return tuple;
        }


        public static async Task<DuoDuoOrderNew> DuoDuoOrder(PddToken pddToken, PDDOrder pddOrder, PddGood pddGood, string daili, string errorMsg)
        {

            //https://mobile.yangkeduo.com/order_checkout.html?
            //sku_id=887573710816&group_id=20545180673&
            //goods_id=37471928938&goods_number=1&page_from=29&
            //_oc_pid=20929712_208780123&_oc_duoduo_type=2&
            //_oc_cps_sign=CC_210729_20929712_208780123_8b7b6848d53c6748fe430746988e8522&
            //_oc_mkt_tr_sc=ddjb_goods_coupon&
            //_oc_mkt_tr_token=di36rcnzybrpuk65hhqi7uyyf4vbua2aplg26wks34g4rottdirfsvbw7md2tja3cgx27lh5z2cyw&_o
            //c_mkt_domain=222&refer_page_element=open_btn&source_channel=0&
            //refer_page_name=goods_detail&
            //_x_ddjb_id=20929712_208780123%7CCC_210729_20929712_208780123_8b7b6848d53c6748fe430746988e8522&

            Dictionary<string, string> dic_other = new Dictionary<string, string>();
            dic_other.Add("sku_id", pddOrder.goods.FirstOrDefault().sku_id);
            dic_other.Add("group_id", pddOrder.group_id);
            dic_other.Add("goods_id", pddOrder.goods.FirstOrDefault().goods_id);
            dic_other.Add("goods_number", pddOrder.goods.FirstOrDefault().sku_number.ToString());
            dic_other.Add("page_from", "29");
            dic_other.Add("_oc_pid", pddGood.duo_duo_pid);
            dic_other.Add("_oc_duoduo_type", "2");
            dic_other.Add("_oc_cps_sign", pddGood.cps_sign);
            dic_other.Add("_oc_mkt_tr_sc", "ddjb_goods_coupon");
            dic_other.Add("_oc_mkt_tr_token", pddGood.mkt_tr_token);
            dic_other.Add("_oc_mkt_domain", "222");
            dic_other.Add("refer_page_element", "open_btn");
            dic_other.Add("source_channel", "0");
            dic_other.Add("refer_page_name", "goods_detail");

            dic_other.Add("_x_ddjb_id", pddGood.duo_duo_pid + "|" + pddGood.cps_sign);

            StringBuilder stringBuilder = new StringBuilder();
            foreach (var item in dic_other)
            {
                stringBuilder.Append(item.Key);
                stringBuilder.Append("=");
                if (!string.IsNullOrWhiteSpace(item.Value))
                {
                    stringBuilder.Append(Uri.EscapeDataString(item.Value));
                }
                stringBuilder.Append("&");
            }

            string url = "https://mobile.yangkeduo.com/order_checkout.html?" + stringBuilder.ToString();

            string html = await PddPiFaApi.GetTransacOrderCouponHtml(pddToken, url, daili);
            errorMsg = "";
            try
            {
                DuoDuoOrderNew duoDuoOrderNew = PaserDuoDuoOrderHtml(html, pddOrder.goods.FirstOrDefault(), errorMsg);
                if (duoDuoOrderNew != null)
                {
                    duoDuoOrderNew.address_id = long.Parse(pddOrder.address_id);
                    duoDuoOrderNew.group_id = pddOrder.group_id;

                }

                return duoDuoOrderNew;
            }
            catch (Exception e)
            {
                LogHelper.Logger.Error("解析错误",e);
                LogHelper.Logger.Error("解析html" + html);
                throw;
            }
        }

        public static async Task<IRestResponse> PinNeiGouOrder(PddToken pddToken, PDDOrder pddOrder, PddGood pddGood, string daili, string errorMsg)
        {
            Dictionary<string, string> dic_other = new Dictionary<string, string>();
            dic_other.Add("_x_sid", "miniprogram");
            dic_other.Add("mini_program_name", "intra_enterprise_sell");
            dic_other.Add("front_env", "20");
            dic_other.Add("pay_app_id", "107");
            dic_other.Add("xcx_trace_id", "");
            dic_other.Add("biz_sn", pddGood.biz_sn);
            dic_other.Add("_oc_mkt_tr_sc", pddGood.mkt_tr_sc);
            dic_other.Add("refer_page_element", "");
            dic_other.Add("goods_number", "1");
            dic_other.Add("mini_program_title", "");
            dic_other.Add("source_channel", "0");
            dic_other.Add("_oc_mkt_domain", pddGood.mkt_domain);
            dic_other.Add("sku_id", pddOrder.goods.FirstOrDefault().sku_id);
            dic_other.Add("page_from", "100005");
            dic_other.Add("_oc_brand_neigou_param", "100005");
            dic_other.Add("group_id", pddOrder.group_id);
            dic_other.Add("goods_id", pddOrder.goods.FirstOrDefault().goods_id);
            dic_other.Add("_oc_mkt_tr_token", pddGood.mkt_tr_token);
            dic_other.Add("mall_id", pddGood.mall_id);
            dic_other.Add("mall_type", "1");
            dic_other.Add("goods_type", "1");
            dic_other.Add("refer_page_sn", "10014");
            dic_other.Add("refer_page_id", "");
            dic_other.Add("refer_page_name", "goods_detail");


            StringBuilder stringBuilder = new StringBuilder();
            foreach (var item in dic_other)
            {
                stringBuilder.Append(item.Key);
                stringBuilder.Append("=");
                if (!string.IsNullOrWhiteSpace(item.Value))
                {
                    stringBuilder.Append(Uri.EscapeDataString(item.Value));
                }
                stringBuilder.Append("&");
            }

            string url = "https://mobile.yangkeduo.com/order_checkout.html?" + stringBuilder.ToString();

            string html = await PddPiFaApi.GetTransacOrderCouponHtml(pddToken, url, daili);
            errorMsg = "";
            PinNeiGoOrder pinNeiGoOrder = PaserOrderHtml(html, pddOrder.goods.FirstOrDefault(), errorMsg);
            if (pinNeiGoOrder == null)
            {
                return null;
            }

            string urlAnti = "https://mobile.yangkeduo.com/proxy/api/order";
            string ant = FackUtil.GetAnti(null, urlAnti);

            if (string.IsNullOrWhiteSpace(ant))
            {
                errorMsg = "下单签名失败";
                return null;
            }

            pinNeiGoOrder.anti_content = ant;
            pinNeiGoOrder.group_id = pddOrder.group_id;
            pinNeiGoOrder.address_id = long.Parse(pddOrder.address_id);
            return await pinduoduo.PddApi.PddOrderPiNeiGou(pddToken, pinNeiGoOrder, daili);
        }


        //https://mobile.yangkeduo.com/order_checkout.html?_oc_merchant_tag=20&sku_id=651761495150&group_id=39839610055&goods_id=161791665492&
        //goods_number=1&page_from=57&_oc_n_mkt_type=1&_oc_trace_mark=199&_oc_n_mkt_tr_sc=duoduo_live
        //&_oc_n_mkt_domain=82&_oc_n_mkt_tr_token=howgixebxtdwatizh76q6zcwwohq4r3hs5wt57szqckal23eloyv3zykxy5f3odrun3ppalel3xow&
        //_oc_live_show_id=20210515_57303109_03&refer_page_element=open_btn&source_channel=0&refer_page_name=goods_detail&
        //refer_page_id=10014_1625913955908_nnb4urdi5o&refer_page_sn=10014
        public static async Task<IRestResponse> ZhiBoOrder(PddToken pddToken, PDDOrder pddOrder, PddGood pddGood, string daili, string errorMsg)
        {
            Dictionary<string, string> dic_other = new Dictionary<string, string>();
            dic_other.Add("_oc_merchant_tag", "20");
            dic_other.Add("sku_id", pddOrder.goods.FirstOrDefault().sku_id);
            dic_other.Add("group_id", pddOrder.group_id);
            dic_other.Add("goods_id", pddOrder.goods.FirstOrDefault().goods_id);
            dic_other.Add("goods_number", "1");

            dic_other.Add("_oc_mkt_tr_sc", pddGood.mkt_tr_sc);
            dic_other.Add("_oc_n_mkt_type", "1");
            dic_other.Add("_oc_trace_mark", "199");
            dic_other.Add("_oc_n_mkt_tr_sc", "duoduo_live");
            dic_other.Add("_oc_n_mkt_domain", pddGood.mkt_domain);
            dic_other.Add("_oc_n_mkt_tr_token", pddGood.mkt_tr_token);
            dic_other.Add("_oc_brand_neigou_param", "100005");

            dic_other.Add("_oc_live_show_id", pddGood.live_show_id);

            dic_other.Add("refer_page_element", "open_btn");
            dic_other.Add("refer_page_sn", "10014");
            dic_other.Add("refer_page_id", "");
            dic_other.Add("refer_page_name", "goods_detail");

            dic_other.Add("source_channel", "0");

            dic_other.Add("page_from", "100005");



            StringBuilder stringBuilder = new StringBuilder();
            foreach (var item in dic_other)
            {
                stringBuilder.Append(item.Key);
                stringBuilder.Append("=");
                if (!string.IsNullOrWhiteSpace(item.Value))
                {
                    stringBuilder.Append(Uri.EscapeDataString(item.Value));
                }
                stringBuilder.Append("&");
            }

            string url = "https://mobile.yangkeduo.com/order_checkout.html?" + stringBuilder.ToString();

            string html = await PddPiFaApi.GetTransacOrderCouponHtml(pddToken, url, daili);
            errorMsg = "";
            ZhiBoOrder zhiboOrder = null;
            try { 
                  zhiboOrder = PaserZhiBoOrderHtml(html, pddOrder.goods.FirstOrDefault(), errorMsg);
               
            }
            catch (Exception e)
            {
                LogHelper.Logger.Error("解析错误",e);
                LogHelper.Logger.Error("解析html" + html);
                throw;
            }

            if (zhiboOrder == null)
            {
                return null;
            }

            string urlAnti = "https://mobile.yangkeduo.com/proxy/api/order";
            string ant = FackUtil.GetAnti(null, urlAnti);

            if (string.IsNullOrWhiteSpace(ant))
            {
                errorMsg = "下单签名失败";
                return null;
            }

            zhiboOrder.anti_content = ant;
            zhiboOrder.group_id = pddOrder.group_id;
            zhiboOrder.address_id = long.Parse(pddOrder.address_id);
            return await pinduoduo.PddApi.PddOrderPiNeiGou(pddToken, zhiboOrder, daili);
        }


        private static DuoDuoOrderNew PaserDuoDuoOrderHtml(string html, Goods goods, string errorMsg)
        {
            Regex reg = new Regex("window.rawData=(?<key2>.*?)};");
            Match match = reg.Match(html);
            string tempStr = match.Groups["key2"].Value;
            if (string.IsNullOrWhiteSpace(tempStr))
            {
                LogHelper.Logger.Debug("解析数据失败：" + html);
                errorMsg = "解析数据失败";
                return null;
            }
            DuoDuoOrderNew duoDuoOrderNew = new DuoDuoOrderNew();
            duoDuoOrderNew.goods = new List<GoodsItem>();

            var jo = JObject.Parse(tempStr + " }");

            var pageFrom = jo["store"]["pageFrom"].ToObject<int>();
            var mkt_tr_sc = jo["store"]["extendMap"]["mkt_tr_sc"].ToString();
            var mkt_domain = jo["store"]["extendMap"]["mkt_domain"].ToString();
            var cps_sign = jo["store"]["extendMap"]["cps_sign"].ToString();
            var biz_type = jo["store"]["extendMap"]["biz_type"].ToObject<int>();
            var original_front_env = jo["store"]["extendMap"]["original_front_env"].ToObject<int>();
            var create_order_token = jo["store"]["extendMap"]["create_order_token"].ToString();
            var create_order_msg = jo["store"]["extendMap"]["create_order_msg"].ToString();
            var mkt_tr_token = jo["store"]["extendMap"]["mkt_tr_token"].ToString();
            var current_front_env = jo["store"]["extendMap"]["current_front_env"].ToObject<int>();


            var promotion_id = jo["store"]["promotionInfo"]["shopPromotion"]?["promotionIdentitVo"]?["promotion_id"]?.ToString();
            var shop_discount = jo["store"]["promotionInfo"]?["shopPromotion"]?["promotionIdentitVo"]?["extension"]?.SelectToken("shop_discount")?.ToString();

            var mall_id = jo["store"]["promotionInfo"]?["shopPromotion"]?["promotionIdentitVo"]?["mall_id"].ToObject<int>();
            var promotion_type = jo["store"]["promotionInfo"]?["shopPromotion"]?["promotionIdentitVo"]?["promotion_type"]?.ToObject<int>();

            duoDuoOrderNew.promotion_union_vo = new Promotion_union_vo();
            duoDuoOrderNew.promotion_union_vo.single_promotion_list = new List<Single_promotion_listItem>();
            Single_promotion_listItem single_Promotion_ListItem = new Single_promotion_listItem();
            single_Promotion_ListItem.sku_ids = new List<string>();
            single_Promotion_ListItem.promotion_id = promotion_id;
            single_Promotion_ListItem.extension = new Extension();
            single_Promotion_ListItem.extension.shop_discount = !string.IsNullOrWhiteSpace(shop_discount) ? shop_discount : "";
            single_Promotion_ListItem.mall_id = mall_id.GetValueOrDefault();
            single_Promotion_ListItem.promotion_type = promotion_type.GetValueOrDefault();

            if (promotion_id != "-1" && !string.IsNullOrWhiteSpace(promotion_id))
            {
                 duoDuoOrderNew.promotion_union_vo.single_promotion_list.Add(single_Promotion_ListItem);
            }
            duoDuoOrderNew.goods.Add(new GoodsItem(goods));

            duoDuoOrderNew.page_from = pageFrom;
            duoDuoOrderNew.attribute_fields = new DuoDuoAttribute_fieldsNew();
            duoDuoOrderNew.attribute_fields.biz_type = biz_type;
            duoDuoOrderNew.attribute_fields.cps_sign = cps_sign;
            duoDuoOrderNew.attribute_fields.mkt_tr_sc = mkt_tr_sc;
            duoDuoOrderNew.attribute_fields.mkt_domain = mkt_domain;
            duoDuoOrderNew.attribute_fields.create_order_token = create_order_token;
            duoDuoOrderNew.attribute_fields.create_order_msg = create_order_msg;
            duoDuoOrderNew.attribute_fields.mkt_tr_token = mkt_tr_token;
            duoDuoOrderNew.attribute_fields.original_front_env = original_front_env;
            duoDuoOrderNew.attribute_fields.current_front_env = current_front_env;


            duoDuoOrderNew.source_channel = "0";
            duoDuoOrderNew.source_type = 0;
            duoDuoOrderNew.biz_type = 0;
            duoDuoOrderNew.type = 2;
            duoDuoOrderNew.version = 1;

            duoDuoOrderNew.is_app = "0";
            duoDuoOrderNew.pay_app_id = 38;
            duoDuoOrderNew.page_from = 29;
            duoDuoOrderNew.page_id = "";
            duoDuoOrderNew.anti_content = "";

            return duoDuoOrderNew;
        }

        private static PinNeiGoOrder PaserOrderHtml(string html, Goods goods, string errorMsg)
        {
            Regex reg = new Regex("window.rawData=(?<key2>.*?)};");
            Match match = reg.Match(html);
            string tempStr = match.Groups["key2"].Value;
            if (string.IsNullOrWhiteSpace(tempStr))
            {
                LogHelper.Logger.Debug("解析数据失败：" + html);
                errorMsg = "解析数据失败";
                return null;
            }
            PinNeiGoOrder pinNeiGoOrder = new PinNeiGoOrder();
            pinNeiGoOrder.goods = new List<GoodsItem>();

            var jo = JObject.Parse(tempStr + " }");

            var pageFrom = jo["store"]["pageFrom"].ToObject<int>();
            var mkt_tr_sc = jo["store"]["extendMap"]["mkt_tr_sc"].ToString();
            var create_order_token = jo["store"]["extendMap"]["create_order_token"].ToString();
            var create_order_msg = jo["store"]["extendMap"]["create_order_msg"].ToString();
            var mkt_tr_token = jo["store"]["extendMap"]["mkt_tr_token"].ToString();
            var current_front_env = jo["store"]["extendMap"]["current_front_env"].ToObject<int>();

            pinNeiGoOrder.goods.Add(new GoodsItem(goods));

            pinNeiGoOrder.page_from = pageFrom;
            pinNeiGoOrder.attribute_fields.mkt_tr_sc = mkt_tr_sc;
            pinNeiGoOrder.attribute_fields.create_order_token = create_order_token;
            pinNeiGoOrder.attribute_fields.create_order_msg = create_order_msg;
            pinNeiGoOrder.attribute_fields.mkt_tr_token = mkt_tr_token;
            pinNeiGoOrder.attribute_fields.current_front_env = current_front_env;

            return pinNeiGoOrder;
        }

        private static ZhiBoOrder PaserZhiBoOrderHtml(string html, Goods goods, string errorMsg)
        {
            Regex reg = new Regex("window.rawData=(?<key2>.*?)};");
            Match match = reg.Match(html);
            string tempStr = match.Groups["key2"].Value;
            if (string.IsNullOrWhiteSpace(tempStr))
            {
                LogHelper.Logger.Debug("解析数据失败：" + html);
                errorMsg = "解析数据失败";
                return null;
            }
            ZhiBoOrder zhiboOrder = new ZhiBoOrder();
            zhiboOrder.goods = new List<GoodsItem>();

            var jo = JObject.Parse(tempStr + " }");

            var pageFrom = jo["store"]["pageFrom"].ToObject<int>();

            var create_order_token = jo["store"]["extendMap"]["create_order_token"].ToString();
            var create_order_msg = jo["store"]["extendMap"]["create_order_msg"].ToString();
            //var create_order_check = jo["store"]["extendMap"]["create_order_check"].ToString();
            var current_front_env = jo["store"]["extendMap"]["current_front_env"].ToObject<int>();

            var live_show_id = jo["store"]["extendMap"]["live_show_id"].ToString();
            var n_mkt_domain = jo["store"]["extendMap"]["n_mkt_domain"].ToString();
            var n_mkt_tr_sc = jo["store"]["extendMap"]["n_mkt_tr_sc"].ToString();
            var n_mkt_tr_token = jo["store"]["extendMap"]["n_mkt_tr_token"].ToString();

            zhiboOrder.goods.Add(new GoodsItem(goods));

            zhiboOrder.page_from = pageFrom;
            zhiboOrder.attribute_fields.n_mkt_tr_sc = n_mkt_tr_sc;
            zhiboOrder.attribute_fields.n_mkt_domain = n_mkt_domain;
            zhiboOrder.attribute_fields.create_order_token = create_order_token;
            //zhiboOrder.attribute_fields.create_order_check = create_order_check;
            zhiboOrder.attribute_fields.create_order_msg = create_order_msg;
            zhiboOrder.attribute_fields.n_mkt_tr_token = n_mkt_tr_token;
            zhiboOrder.attribute_fields.live_show_id = live_show_id;


            zhiboOrder.attribute_fields.current_front_env = current_front_env;

            return zhiboOrder;
        }

        public static PddAddress GetAddress(string addressStr, ref PddAddressDBModel pddAddressDBModel)
        {
            if (string.IsNullOrWhiteSpace(addressStr))
            {
                return null;
            }
            if (pddAddressDBModel == null)
            {
                return null;
            }

            PddAddress pddAddress = new PddAddress();
            IEnumerable<AreaModel> areaModelList = DataBaseHelper.SqLiteDBCon.GetAll<AreaModel>();

            string[] sArray1 = addressStr.Split(new char[4] { '-', '-', '-', '-' }, StringSplitOptions.RemoveEmptyEntries);
            if (sArray1.Length != 3)
            {
                return null;
            }
            string name = sArray1[0];
            string mobile = sArray1[1];
            string address = sArray1[2];

            pddAddressDBModel.name = name;
            pddAddressDBModel.mobile = mobile;
            pddAddressDBModel.address = address;




            string[] addressArr = pddAddressDBModel.address.Split(' ');
            if (addressArr.Length != 4)
            {
                return null;
            }

            var sheng = areaModelList.Where(x =>
            {
                return x.region_type == 1 && (x.region_name.Contains(addressArr[0]) || addressArr[0].Contains(x.region_name));
            }).FirstOrDefault();
            if (sheng == null)
            {
                return null;
            }

            var shi = areaModelList.Where(x =>
            {
                return x.region_type == 2 && sheng.region_id == x.parent_id && (x.region_name.Contains(addressArr[1]) || addressArr[1].Contains(x.region_name));
            }).FirstOrDefault();

            if (shi == null)
            {
                return null;
            }

            var xian = areaModelList.Where(x =>
            {
                return x.region_type == 3 && shi.region_id == x.parent_id && (x.region_name.Contains(addressArr[2]) || addressArr[2].Contains(x.region_name));
            }).FirstOrDefault();

            if (xian == null)
            {
                return null;
            }
            pddAddress.city_id = shi.region_id;
            pddAddress.district_id = xian.region_id;
            pddAddress.province_id = sheng.region_id;

            //if (nameCheckBox.Checked)
            //{
            //    if (nameBeforeRadioButton.Checked)
            //    {
            //        pddAddress.name = this.NamePrefixTextBox.Text + pddAddressDBModel.name;
            //    }
            //    else
            //    {
            //        pddAddress.name = pddAddressDBModel.name + this.NamePrefixTextBox.Text;
            //    }
            //}
            //else
            //{
            pddAddress.name = pddAddressDBModel.name;

            //if (addressCheckBox.Checked)
            //{
            //    if (addressCeforeRadioButton.Checked)
            //    {
            //        pddAddress.address = this.AddressPrefixTextBox.Text + addressArr[3];
            //    }
            //    else
            //    {
            //        pddAddress.address = addressArr[3] + this.AddressPrefixTextBox.Text;
            //    }
            //}
            //else
            //{
            pddAddress.address = addressArr[3];
            //}

            pddAddress.mobile = pddAddressDBModel.mobile;

            pddAddress.is_default = "0";




            return pddAddress;
            //var res = await PddApi.AddAddress(pddToken, pddAddress, daili);
            //Msg("地址设置：" + pddAddressDBModel.address);
            //if (res.StatusCode == HttpStatusCode.OK && !string.IsNullOrWhiteSpace(res.Content))
            //{
            //    dynamic dyn = JsonConvert.DeserializeObject(res.Content);
            //    address_id = dyn.address_id;

            //    if (isDelAddress)
            //    {
            //        Msg("自动删除本地地址：" + pddAddressDBModel.address);
            //        DataBaseHelper.SqLiteDBCon.Delete(pddAddressDBModel);
            //        pddAddressDBModelList.ToList().RemoveAt(index);
            //    }
            //    return address_id;
            //}
            //else 
            //{
            //    LogHelper.Logger.Debug("地址设置异常："+ pddAddressDBModel.address);
            //    LogHelper.Logger.Debug("地址设置异常："+ res.Content);
            //}

            //return address_id;

        }



        //private async Task<Tuple<Order, PayResult>> PiFa(PddGood pdd, PddToken pddToken, CreateOrderItemListItem createOrderItemListItem, string addressId, string daili, bool singBuy)
        //{
        //    string urlAnti = "https://mms.pinduoduo.com/pifa/goods/singleBuy";
        //    string ant = FackUtil.GetAnti(null, urlAnti);

        //    if (string.IsNullOrWhiteSpace(ant))
        //    {
        //        Msg("下单签名失败，请在中间切换个网试试看行不", true);
        //        return new Tuple<Order, PayResult>(null, PayResult.Ignore);
        //    }

        //    var res = await PddPiFaApi.SingleBuy(pddToken, createOrderItemListItem, ant, daili);
        //    if (res.StatusCode != HttpStatusCode.OK)
        //    {
        //        LogHelper.Logger.Debug("批发下单错误：" + res.Content);
        //        Msg("批发下单失败", true);
        //        return new Tuple<Order, PayResult>(null, PayResult.Ignore);
        //    }

        //    var jo = JObject.Parse(res.Content);

        //    var success = jo["success"].ToString();
        //    var errorCode = jo["errorCode"].ToString();
        //    var errorMsg = jo["errorMsg"].ToString();
        //    if (success.ToLower() != "true")
        //    {
        //        if (errorCode == "6000005")
        //        {
        //            Msg(errorMsg, true);
        //            return new Tuple<Order, PayResult>(null, PayResult.Ignore);
        //        }
        //        LogHelper.Logger.Debug("批发下单错误：" + res.Content);
        //        Msg("批发下单失败", true);
        //        return new Tuple<Order, PayResult>(null, PayResult.Ignore);
        //    }

        //    var qrKey = jo["result"]["qrKey"].ToString();

        //    if (string.IsNullOrWhiteSpace(qrKey))
        //    {
        //        LogHelper.Logger.Debug("批发下单错误：" + res.Content);
        //        Msg("批发下单失败", true);
        //        return new Tuple<Order, PayResult>(null, PayResult.Ignore);
        //    }
        //    var curl = jo["result"]["curl"].ToString();

        //    string html = await PddPiFaApi.GetTransacOrderCouponHtml(pddToken, curl, daili);
        //    var pifaClientOrderCreate = PaserOrderHtml(html);
        //    if (pifaClientOrderCreate == null)
        //    {
        //        return new Tuple<Order, PayResult>(null, PayResult.Ignore);
        //    }
        //    urlAnti = "https://mobile.yangkeduo.com/proxy/api/api/pifa-client/order/order_create";
        //    ant = FackUtil.GetAnti(null, urlAnti);

        //    pifaClientOrderCreate.secret_key = qrKey;
        //    pifaClientOrderCreate.anti_content = ant;
        //    pifaClientOrderCreate.page_id = "";
        //    pifaClientOrderCreate.address_id = double.Parse(addressId);
        //    res = await PddPiFaApi.PiFaOrderCreate(pddToken, pifaClientOrderCreate, daili);
        //    if (res.StatusCode != HttpStatusCode.OK)
        //    {
        //        Msg("批发下单失败", true);
        //        LogHelper.Logger.Debug("批发下单错误：" + res.Content);
        //    }

        //    jo = JObject.Parse(res.Content);

        //    success = jo["success"].ToString();

        //    if (success.ToLower() != "true")
        //    {
        //        Msg("批发下单失败", true);
        //        LogHelper.Logger.Debug("批发下单错误：" + res.Content);
        //        return new Tuple<Order, PayResult>(null, PayResult.Ignore);
        //    }

        //    var order_sns = jo["result"]["order_sns"].FirstOrDefault()?.ToString();
        //    var parent_order_sn = jo["result"]["parent_order_sn"].ToString();

        //    pddToken.last_order_sn = order_sns;
        //    UpdateOrderSn(pddToken);
        //    pddTokenService.UpdateToken(pddToken, true);

        //    Msg("下单成功，订单号：" + parent_order_sn);

        //    Order order = new Order();
        //    order.goodsId = createOrderItemListItem.goodsId.ToString();
        //    order.orderSn = order_sns;
        //    order.parent_order_sn = parent_order_sn;
        //    order.uid = pddToken.pdd_user_id;
        //    order.buyTime = DateTime.Now.ToString();
        //    order.skuNumber = createOrderItemListItem.skuNum.ToString();
        //    order.order_type = "批发订单";

        //    if (this.OnlyPrePayRadioButton.Checked)
        //    {
        //        order.orderState = "未支付";
        //        await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);
        //        Msg("先下单后支付模式，任务完成");
        //        return new Tuple<Order, PayResult>(order, PayResult.OK);
        //    }


        //    res = await PddPiFaApi.PiFPrepay(pddToken, parent_order_sn, daili);

        //    if (res.StatusCode != HttpStatusCode.OK)
        //    {
        //        Msg("批发下单失败", true);
        //        LogHelper.Logger.Debug("批发下单错误：" + res.Content);
        //        return new Tuple<Order, PayResult>(null, PayResult.Ignore);
        //    }

        //    Msg("生成支付链接成功");

        //    jo = JObject.Parse(res.Content);
        //    var query = jo["query"];
        //    var total_fee = jo["query"]["total_fee"].ToString();

        //    var gateway_url = jo["gateway_url"];

        //    StringBuilder stringBuilder = new StringBuilder();
        //    foreach (JToken grandChild in query)
        //    {
        //        var p = grandChild as JProperty;
        //        string s = p.Name + ":" + p.Value;
        //        stringBuilder.Append(p.Name);
        //        stringBuilder.Append("=");
        //        stringBuilder.Append(Uri.EscapeDataString(p.Value.ToString()));
        //        stringBuilder.Append("&");
        //    }
        //    stringBuilder.Remove(stringBuilder.Length - 1, 1);
        //    string url = gateway_url + "?" + stringBuilder.ToString();
        //    order.pay_url = url;
        //    order.goodsMoney = double.Parse(total_fee) * 100 + "";
        //    return new Tuple<Order, PayResult>(order, PayResult.OK);

        //    //   await DataBaseHelper.SqLiteDBCon.InsertAsync<Order>(order);

        //    //int PayStartIntervalTime = this.PayStartIntervalTimeTextBox.IntValue;
        //    //int PayEndIntervalTime = this.PayEndIntervalTimeTextBox.IntValue;

        //    //if (PayStartIntervalTime > 0 && PayEndIntervalTime > 0 && PayEndIntervalTime > PayStartIntervalTime)
        //    //{
        //    //    Random r = new Random();
        //    //    int IntervalTime = r.Next(PayStartIntervalTime, PayEndIntervalTime);
        //    //    Msg("付款间隔" + IntervalTime + "秒");
        //    //    await Task.Delay(TimeSpan.FromSeconds(IntervalTime));
        //    //}

        //    //return AutoPay(url, this.PayPassword.Text, !singBuy) ? PayResult.OK : PayResult.Ignore;

        //}


        //private PifaClientOrderCreate PaserOrderHtml(string html)
        //{
        //    Regex reg = new Regex("window.rawData= (?<key2>.*?)};");
        //    Match match = reg.Match(html);
        //    string tempStr = match.Groups["key2"].Value;
        //    if (string.IsNullOrWhiteSpace(tempStr))
        //    {
        //        Msg("解析数据失败", true);
        //        return null;
        //    }
        //    PifaClientOrderCreate pifaClientOrderCreate = new PifaClientOrderCreate();
        //    pifaClientOrderCreate.sku_vos = new List<Sku_vosItem>();
        //    Sku_vosItem sku_VosItem = new Sku_vosItem();
        //    var jo = JObject.Parse(tempStr + " }");
        //    var goodsListStore = jo["store"]["goodsListStore"]["goodsList"].ToArray();
        //    var frontEnv = jo["store"]["envStore"]["frontEnv"].ToObject<int>();
        //    //var addressId = jo["store"]["addressInfoStore"]["addressId"].ToObject<double>();

        //    var goods = goodsListStore.FirstOrDefault();
        //    string goods_id = goods["goodsId"].ToString();
        //    string group_id = goods["groupId"].ToString();
        //    string sku_id = goods["skuId"].ToString();
        //    string sku_number = goods["skuNumber"].ToString();

        //    sku_VosItem.goods_id = double.Parse(goods_id);
        //    sku_VosItem.group_id = double.Parse(group_id);
        //    sku_VosItem.sku_id = double.Parse(sku_id);
        //    sku_VosItem.sku_number = int.Parse(sku_number);
        //    pifaClientOrderCreate.front_env = frontEnv;
        //    pifaClientOrderCreate.sku_vos.Add(sku_VosItem);

        //    return pifaClientOrderCreate;
        //}



    }
}
